package org.testmyapp.tasks.processone;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.enterprise.context.SessionScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Named;

import org.activiti.cdi.BusinessProcessEvent;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.testmyapp.entities.Access;
import org.testmyapp.persistence.BusinessObjectPersistenceProvider;

@Named(value="processOneEndListener")
@SessionScoped
public class ProcessOneEndListener implements ExecutionListener, Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3046663720930101982L;
	
	@Inject
	private BusinessObjectPersistenceProvider bopp;

	public void notify(DelegateExecution execution) throws Exception {
		if(execution.getEventName().equals(EVENTNAME_END)) {
			String persiList = (String) execution.getVariable("persistenceList");
			if(persiList == null) {
				return;
			}
			String[] split = persiList.split(",");
			for(String s : split) {
				String[] keys = s.split(":");
				String sql = "select a from " + Access.tableName + " a where a.id = :kid";
				Map<String,Object> params = new HashMap<String,Object>();
				params.put("pid", keys[0]);
				Access fromDb = bopp.querySingle(sql, params, Access.class);
				fromDb.setDate(new Date());
				bopp.persist(fromDb);
				throw new RuntimeException("pooooooooooooooop but fucktown");
			}
		}
		if(execution.getEventName().equals(EVENTNAME_START)) {
			throw new RuntimeException("pooooooooooooooop but fucktown");
		}
	}
	
	public void test(DelegateExecution execution) {
		boolean sup;
		if(bopp != null) {
			throw new RuntimeException("pooooooooooooooop but good");
		}
		else {
			throw new RuntimeException("pooooooooooooooop but not good");
		}
	}
	
	public void catchActivitiEvent(@Observes BusinessProcessEvent bpe) {
		boolean sup;
		if(bopp != null) {
			throw new RuntimeException("pooooooooooooooop but good");
		}
		else {
			throw new RuntimeException("pooooooooooooooop but not good");
		}
	}

}
